package net.streaming.rtp;

import java.io.DataInputStream;
import java.io.IOException;

public class RtpUtil {
    
	public static RtpHead getRtpHead(byte[] buf /*12 bytes*/) {
		RtpHead head = new RtpHead();
		byte b = buf[0];
		
		head.setVersion((b&0xc0)>>6);
		head.setPadding((b&0x20)>>5);
		head.setExtension((b&0x10)>>3);
		head.setCSRC_count(b&0x0f);
		
		byte b2 = buf[1];
		head.setMarker((b2&0x80)>>7);
		head.setPayload_type(b2&0x7f);

		head.setSeq_num(getShort(buf, 2));
		head.setTimestamp(getInt(buf, 4));
		head.setSSRC(getInt(buf, 8));
		
		return head;
	}

	public static RtpHead getRtpHead(DataInputStream dis) throws IOException {
		RtpHead head = new RtpHead();
		
		byte b = dis.readByte();
		head.setVersion((b&0xc0)>>6);
		head.setPadding((b&0x20)>>5);
		head.setExtension((b&0x10)>>3);
		head.setCSRC_count(b&0x0f);
		
		byte b2 = dis.readByte();
		head.setMarker((b2&0x80)>>7);
		head.setPayload_type(b2&0x7f);
		
		head.setSeq_num(dis.readShort());
		head.setTimestamp(dis.readInt());
		head.setSSRC(dis.readInt());
		
		return head;
	}

	private static short getShort(byte[] buf, int pos){
		int n1 = buf[pos+0] & 0xff;
		int n2 = buf[pos+1] & 0xff;
		int n = n1 | n2<<8;
		n &= 0x0ffff;
		return (short) n;
	}
	
	private static int getInt(byte[] buf, int pos){
		int n = (buf[pos+0]&0x00ff)|((buf[pos+1]<<8)&0xff00)|((buf[pos+2]<<24)>>>8)|((buf[pos+3]<<24));
		return n;
	}
	
	//////////////////


}